package rabbitmq_Demo;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RabbitmqConsumer{
    private static final String QUEUE_NAME="queue_demo";
//private final static String QUEUE_NAME = "hello";
    private static final String IP_ADDRESS="192.168.42.130";
    private static final int PORT=15672;

    public static void main(String[] args)throws Exception {
        Address[] addresses =new Address[]{
                new Address(IP_ADDRESS,PORT)
        };
        while (true) {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setUsername("root");
            factory.setPassword("root");
            Connection connection = factory.newConnection(addresses);//创建连接
            final Channel channel = connection.createChannel();//创建信道
            channel.basicQos(64);//设置客户端接收未被ack的消息个数
            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("recv message=" + new String(body));
                    try {

                        TimeUnit.SECONDS.sleep(1);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    channel.basicAck(envelope.getDeliveryTag(), false);
                    //等待回调函数执行完毕，关闭资源
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        channel.close();
                    } catch (TimeoutException e) {
                        e.printStackTrace();
                    }
                    connection.close();

                }
            };

        }
    }





}
